package cn.tedu.ivos.base.security;

import cn.tedu.ivos.base.response.JsonResult;
import cn.tedu.ivos.base.response.StatusCode;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 自定义权限不足处理类，实现了AccessDeniedHandler接口
 * 当用户没有足够的权限访问资源时，该类将被调用以处理权限不足的异常
 */
@Slf4j
@Service
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    /**
     * 处理权限不足的异常
     * @param request  当前的HTTP请求对象
     * @param response 当前的HTTP响应对象
     * @param accessDeniedException 权限不足异常对象
     * @throws IOException 如果在处理过程中发生I/O错误
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
        log.debug("权限不足");
        //设置HTTP响应状态为403，表示禁止访问
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        //设置响应内容类型为JSON，以UTF-8编码
        response.setContentType("application/json;charset=UTF-8");
        //获取响应的打印写手，用于写入响应内容
        PrintWriter writer = response.getWriter();
        //构建一个表示未登录的JSON结果对象
        JsonResult result = new JsonResult(StatusCode.NOT_LOGIN);
        //将JSON结果对象转换为JSON字符串并写入响应
        writer.write(JSON.toJSONString(result));
        //刷新写手并关闭它
        writer.flush();
        writer.close();
    }
}